#!/bin/bash
export 'PS4=[`date +"%Y-%m-%d %H:%M:%S"`]`basename $0`.$LINENO+ '

source  ../lib/gitlib.sh
source  ../lib/lib.sh

git_root=/jenkins_home/source_cache
git_orig_url=http://peulerosci@dgggit09-rd.huawei.com/a/euleros/third_party/open_source/kernelspace/linux-4.19-euleros
git_orig_name=linux-4.19-euleros
git_orig_branch=next_src
git_dest_url=http://peulerosci@dgggit09-rd.huawei.com/a/euleros/third_party/open_source/kernelspace/linux-4.19
git_dest_name=linux-4.19
git_dest_branch=next_kernel

added_key="[dgggit09-rd.huawei.com]:29418,[10.1.21.40]:29418 ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAxhN+TnUC8a91hpMJmuYMOl+X7S2XlyGhhIQEBvZTcjqF/FXN2u9Jn4SkeXsAi6J+P1q3nFKbgqQKpug2f41Q6xufXn4wsnACcjVAzVmSSe+qvMUh84oiI7j7c7MZ9iQhxgMzrJIMoP20wsVjEyQtT2jlrxb8+h6dzq+sk2HhX4wA+rsIOFrSQvKdIjrphCoVJ+vadX+dtk5BD+Etdu22XlPl3AfZONpssPmEc/hM96u44NtHE+BujDhBhXYW8VKYKW1ZiQ0x/27YR2jss572jlEegOCMq/GmoiRwWM7Y7ZBZ8rrEg85lpjIDKCfh8r1Hiz6wrrWfQGdSHukUEL2aqQ=="

added_key_id_rsa="ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDU/h5m79Voc4Kzyf9bNardbQYuSicnOc4ERv5tAtZOgAZwV9s4M4J7++ZxugFPUcbJs9nIHwlhBNVSxWcgnp7DlfEzysuv72dIwrEobdEUiIpKv9GuHNWvJRM0ltRVIlO1P4iUAwqPXaCCMOEARKL3qVNVmuZM1UcgGOLBxq2V/mqJdf8S1vYTu7lOxwhSHSJLxzhaYNViOKiPrjMaVRkieOLLLiqjZE4pgXgM3bl+2huR9Gamo2ZWTCLJ2Y+Ueek4tfHMvzTurXFYEVCjBJfd6YpJ55wh6HqiXsd5biyM2bNECGSDnRGk52qLh43RR+BLxB1soCpoULP/T52G6QSX eulerosci@huawei.com"

if cat /root/.ssh/known_hosts | grep "dgggit09-rd.huawei.com" > /dev/null;then
    echo "Key is OK"
else
    echo "$added_key" >> /root/.ssh/known_hosts
fi

echo "$added_key_id_rsa" > /root/.ssh/id_rsa.pub
chmod 644 /root/.ssh/id_rsa.pub

mkdir -p ${git_root}
cd ${git_root}

#rm -rf linux-4.19 linux-4.19-euleros
#更新目录
git_update ${git_orig_url} ${git_orig_branch}
if [ -d ${git_root}/${git_dest_name} ]; then
    cd ${git_root}/${git_dest_name}
    git reset --hard HEAD~2
fi
git_update ${git_dest_url} ${git_dest_branch}
pushd ${git_root}/${git_dest_name}
curl -kLo `git rev-parse --git-dir`/hooks/commit-msg http://peulerosci@dgggit09-rd.huawei.com/tools/hooks/commit-msg
chmod +x `git rev-parse --git-dir`/hooks/commit-msg


#判断是否首次提交
pushd ${git_root}/${git_dest_name}
ssh -p 29418 peulerosci@dgggit09-rd.huawei.com gerrit query project:euleros/third_party/open_source/kernelspace/linux-4.19 limit:1 status:open branch:${git_dest_branch} owner:peulerosci --current-patch-set > /tmp/kernel-src-to-build
if cat /tmp/kernel-src-to-build | grep 'rowCount: 1' &> /dev/null; then
    echo "the last linux-4.19 is open status"
    cur_ref=$(cat /tmp/kernel-src-to-build | grep 'ref: refs' | awk '{print $2}')
    cur_revision=$(cat /tmp/kernel-src-to-build | grep 'revision:' | awk '{print $2}')
    cur_status=$(cat /tmp/kernel-src-to-build | grep 'status:' | awk '{print $2}')
    ChangeId=$(cat /tmp/kernel-src-to-build | grep 'Change-Id: ' | awk '{print $2}')
else
    echo "the last linux-4.19 is merge status"
    ssh -p 29418 peulerosci@dgggit09-rd.huawei.com gerrit query project:euleros/third_party/open_source/kernelspace/linux-4.19 limit:1 status:merge branch:${git_dest_branch} owner:peulerosci --current-patch-set > /tmp/kernel-src-to-build
    cur_ref=$(cat /tmp/kernel-src-to-build | grep 'ref: refs' | awk '{print $2}')
    cur_revision=$(cat /tmp/kernel-src-to-build | grep 'revision:' | awk '{print $2}')
    cur_status=$(cat /tmp/kernel-src-to-build | grep 'status:' | awk '{print $2}')
    ChangeId=''
fi
ssh -p 29418 peulerosci@dgggit09-rd.huawei.com gerrit query project:euleros/third_party/open_source/kernelspace/linux-4.19 limit:1 status:merge branch:${git_dest_branch} owner:peulerosci --current-patch-set > /tmp/kernel_latest_merged
old_revision=$(cat /tmp/kernel_latest_merged | grep 'revision:' | awk '{print $2}')
#生成目标patch
pushd ${git_root}/${git_orig_name}
rm -rf ./*.patch
git format-patch -1 ${GERRIT_PATCHSET_REVISION}
commit_log=$(git log ${GERRIT_PATCHSET_REVISION} --pretty=format:'%b' -n1 | tac |sed '1,2d'|tac |sed '/Change-Id:/d')
developer_name=$(cat ./*.patch | grep 'From:' | awk -F ' ' '{print $2}')
patch_name=$(ls *.patch)
date_name=$(date +%Y-%m-%d-%H-%M-%S)
#patch_name=$(echo ${GERRIT_CHANGE_SUBJECT#*:} | sed "s/[^[:alnum:]]/-/g")
if git log --no-merges -n1 | grep 'github.com' || git log --no-merges -n1 | grep 'kernel.org' || git log --no-merges -n1 | grep 'redhat.com' || git log --no-merges -n1 | grep 'suse.com' || git log --no-merges -n1 | grep 'centos.org' || git log --no-merges -n1 | grep 'fedoraproject.org' &> /dev/null; then   #开源补丁
    mv ./*.patch ./backport-${date_name}-${patch_name}
    new_patch_name="backport-${date_name}-${patch_name}"
elif git log --no-merges -n1 | grep 'Revert:' &> /dev/null; then
    mv ./*.patch ./huawei-revert-${date_name}-${patch_name}
    new_patch_name="huawei-revert-${date_name}-${patch_name}"
else
    mv ./*.patch ./huawei-${date_name}-${patch_name}
    new_patch_name="huawei-${date_name}-${patch_name}"
fi
sed -i "/DTS\/AR:/d" ${new_patch_name}
sed -i "s/${developer_name}//g" ${new_patch_name}

pushd ${git_root}/${git_dest_name}
    expect -c "
        set timeout -1
        spawn git fetch ${git_dest_url} ${cur_ref}
        expect {
            \"*(yes/no)*\" { send \"yes\r\"; exp_continue }
            \"*Username*\" { send \"peulerosci\r\"; exp_continue }
            \"*Password*\" { send \"EulerOS_123\r\"; exp_continue }
            eof { catch wait result; exit [lindex \$result 3] }
        }
        expect {
            eof { catch wait result; exit [lindex \$result 3] }
        }
"
set +e
    expect -c "
        set timeout -1
        spawn git merge ${cur_revision}
        expect {
            \"*(yes/no)*\" { send \"yes\r\"; exp_continue }
            \"*Username*\" { send \"peulerosci\r\"; exp_continue }
            \"*Password*\" { send \"EulerOS_123\r\"; exp_continue }
            eof { catch wait result; exit [lindex \$result 3] }
        }
        expect {
            eof { catch wait result; exit [lindex \$result 3] }
        }
"
set -e
mv ${git_root}/${git_orig_name}/${new_patch_name} ${git_root}/${git_dest_name}/patches/euleros/
#修改spec文件
for fspec in `ls *.spec`
do
    if grep '%define hwrelease' $fspec &>/dev/null; then
        release=`cat $fspec | grep '%define hwrelease' | awk '{print $3}'`
        if ! echo $release | grep 'h' &>/dev/null; then
            echo "Error: can not find delimit h in $fspec hwrelease"
            exit 1
        fi
        relese_num=`echo $release | awk -F 'h' '{print $2}'`
        let new_release_num=$relese_num+1
        new_release=".h${new_release_num}"
        sed -i "/define hwrelease/s/$release/$new_release/g" $fspec
    else
        echo "Error: can not find hwrelease in $fspec"
        exit 1
    fi
    version_relase=`rpm -q --qf '%{VERSION}-%{RELEASE}\n' --specfile kernel.spec | head -n1`
    changelog="* `date '+%a %b %d %Y'` ${GERRIT_CHANGE_OWNER_EMAIL%%@*}<${GERRIT_CHANGE_OWNER_EMAIL}> - ${version_relase}\n- Type:bugfix\n- ID:NA\n- SUG:restart\n- DESC:${GERRIT_CHANGE_SUBJECT#*:}\n"
    sed -i "/%changelog/a${changelog}" $fspec
done
#修改series.conf文件
echo "patches/euleros/${new_patch_name}" >> series.conf
#提交
owner_name="`echo ${GERRIT_CHANGE_OWNER_NAME:0:1}``echo ${GERRIT_CHANGE_OWNER_NAME} | awk '{print $2}'`"
git config --global user.name ${owner_name}
git config --global user.email ${GERRIT_CHANGE_OWNER_EMAIL}
git add --all
if [ "${cur_status}" == "NEW" ]; then
    git_commit_amend "$GERRIT_CHANGE_SUBJECT

$commit_log
from linux-4.19-euleros: $GERRIT_PATCHSET_REVISION

Change-Id: $ChangeId"
else
    git_commit "$GERRIT_CHANGE_SUBJECT

$commit_log
from linux-4.19-euleros: $GERRIT_PATCHSET_REVISION"    
fi
#push
expect -c "
        set timeout -1
        spawn git push origin HEAD:refs/for/${git_dest_branch}%topic=linux-4.19_src_to_build
        expect {
            \"Password for *\" { send \"EulerOS_123\r\"; exp_continue }
            eof { catch wait result; exit [lindex \$result 3] }
        }
        expect {
            eof { catch wait result; exit [lindex \$result 3] }
        }
"
#状态清零
git reset --hard ${old_revision}
